package cn.xyz.mianshi.utils;

import java.lang.reflect.InvocationTargetException;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

import cn.xyz.commons.utils.DocumentToJavaBean;
import cn.xyz.mianshi.vo.Friends;

/**
 * 数据库 分库分表 变更类
 
 * @author lidaye
 *
 */
@Component
public class UpdateDBVersion {

	private static final Logger log = LoggerFactory.getLogger(UpdateDBVersion.class);
	
	public void updateAddressBook() {
		MongoClient mongoClient = SKBeanUtils.getLocalSpringBeanManager().getMongoClient();
		MongoDatabase database = mongoClient.getDatabase("imapi");
		MongoCollection<Document> collection = database.getCollection("user");
		if(0==collection.count()) {
			log.info("没有 用户数量 不需要 执行 修改 数据库代码 ====>");
			return;
		}
		MongoCollection<Document> addressbook = database.getCollection("AddressBook");	
		Integer userId=10012256;
		//Integer endId=userId+2000;
		MongoCursor<Integer> mongoCursor = collection.distinct("_id",new Document("_id",new Document("$gt",userId)), Integer.class).iterator();
		Document query=null;
		 MongoCursor<Document> iterator=null;
		 Document result=null;
		 long start=System.currentTimeMillis();
		 long oneCount=0;
		 long allCount=0;
		 MongoCollection<Document> collection2=null;
		while (mongoCursor.hasNext()) {
			userId=mongoCursor.next();
			query=new Document("userId",userId);
			 oneCount=addressbook.count(query);
			 if(0==oneCount) {
				 log.info("userId "+userId+" 没有数据 。。。。");
				 continue;
			 }
			 allCount+=oneCount;
			 log.info("userId "+userId+" 的手机联系人 列表正在分表分库 =====》 数量  ===> "+addressbook.count(query));
			  collection2 = SKBeanUtils.getAddressBookManger().getCollection(userId);
			if(0< collection2.count(query)) {
				log.info("userId "+userId+" 分表已存在数据  ====>");
				//continue;
			}
			 iterator = addressbook.find(query).iterator();
			
			 try {
				 while (iterator.hasNext()) {
					 result=iterator.next();
					 if(0<collection2.count(new Document("_id",result.getObjectId("_id")))) {
						 continue;
					 }
					 collection2.insertOne(result);
				}
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					iterator.close();
				}
		}
		log.info("分表执行完毕 总数量  ==》 "+allCount+"  总耗时 "+(System.currentTimeMillis()-start)/1000 +" 秒 =====》");
	}
	
	
	public void update_shikuChatMsgList() {
		MongoClient mongoClient = SKBeanUtils.getLocalSpringBeanManager().getTigMongoClient();
		MongoDatabase database = mongoClient.getDatabase("imapi");
		MongoCollection<Document> collection = database.getCollection("user");
		if(0==collection.count()) {
			log.info("没有 用户数量 不需要 执行 修改 数据库代码 ====>");
			return;
		}
		MongoCollection<Document> addressbook = mongoClient.getDatabase("tigase").getCollection("shiku_msgs");	
		MongoDatabase chatDB = mongoClient.getDatabase("shiku_msgs");
		/**
		 * 开始的用户ID  
		 */
		Integer userId=10004000;
		MongoCursor<Integer> mongoCursor = collection.distinct("_id",new Document("_id",new Document("$gt",userId)), Integer.class).iterator();
		Document query=null;
		 MongoCursor<Document> iterator=null;
		 Document result=null;
		 long start=System.currentTimeMillis();
		 long oneCount=0;
		 long allCount=0;
		 MongoCollection<Document> collection2=null;
		while (mongoCursor.hasNext()) {
			userId=mongoCursor.next();
			query=new Document("sender",userId);
			 oneCount=addressbook.count(query);
			 if(0==oneCount) {
				 log.info("userId "+userId+" 没有数据 。。。。");
				 continue;
			 }
			 allCount+=oneCount;
			 log.info("userId "+userId+" 的单聊聊天记录 列表正在分表分库 =====》 数量  ===> "+addressbook.count(query));
			  collection2 = SKBeanUtils.getTigaseManager().getMongoCollection(chatDB,userId);
			if(0< collection2.count(query)) {
				log.info("userId "+userId+" 分表已存在数据  ====>");
				//continue;
			}
			 iterator = addressbook.find(query).iterator();
			
			 try {
					 while (iterator.hasNext()) {
						 result=iterator.next();
						 if(0<collection2.count(new Document("_id",result.getObjectId("_id")))) {
							 continue;
						 }
						 collection2.insertOne(result);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					iterator.close();
				}
		}
		log.info("分表执行完毕 总数量  ==》 "+allCount+"  总耗时 "+(System.currentTimeMillis()-start)/1000 +" 秒 =====》");
	
	}
	
	
	
	
	public void updateLastChatMsgList() {
		MongoClient mongoClient = SKBeanUtils.getLocalSpringBeanManager().getTigMongoClient();
		MongoDatabase database = mongoClient.getDatabase("imapi");
		MongoCollection<Document> collection = database.getCollection("user");
		if(0==collection.count()) {
			log.info("没有 用户数量 不需要 执行 修改 数据库代码 ====>");
			return;
		}
		MongoCollection<Document> addressbook = mongoClient.getDatabase("tigase").getCollection("shiku_lastChats");	
		MongoDatabase chatDB = mongoClient.getDatabase("shiku_lastChats");
		
		/**
		 * 群聊 最后一条聊天记录表
		 */
		MongoCollection<Document> mucLastCollection = chatDB.getCollection("shiku_lastChats_muc");	
		/**
		 * 开始的用户ID  
		 */
		Integer userId=10004000;
		MongoCursor<Integer> mongoCursor = collection.distinct("_id",new Document("_id",new Document("$gt",userId)), Integer.class).iterator();
		Document query=null;
		 MongoCursor<Document> iterator=null;
		 Document result=null;
		 long start=System.currentTimeMillis();
		 long oneCount=0;
		 long allCount=0;
		 MongoCollection<Document> collection2=null;
		while (mongoCursor.hasNext()) {
			userId=mongoCursor.next();
			query=new Document("userId",userId.toString());
			 oneCount=addressbook.count(query);
			 if(0==oneCount) {
				 log.info("userId "+userId+" 没有数据 。。。。");
				 continue;
			 }
			 allCount+=oneCount;
			 log.info("userId "+userId+" 的单聊 最后一条记录 列表正在分表分库 =====》 数量  ===> "+addressbook.count(query));
			  collection2 = SKBeanUtils.getTigaseManager().getMongoCollection(chatDB,userId);
			if(0< collection2.count(query)) {
				log.info("userId "+userId+" 分表已存在数据  ====>");
				//continue;
			}
			 iterator = addressbook.find(query).iterator();
			 
			 try {
				 while (iterator.hasNext()) {
					 result=iterator.next();
					 if(1==result.getInteger("isRoom")) {
						 if(0<mucLastCollection.count(new Document("_id",result.getObjectId("_id")))) {
							 continue;
						 } 
						 mucLastCollection.insertOne(result);
					 }
					 if(0<collection2.count(new Document("_id",result.getObjectId("_id")))) {
						 continue;
					 }
					 collection2.insertOne(result);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				iterator.close();
			}
		}
		log.info("分表执行完毕 总数量  ==》 "+allCount+"  总耗时 "+(System.currentTimeMillis()-start)/1000 +" 秒 =====》");
	
	}
	
	/**
	 * 分库分表 群成员
	 */
	public void updateRoomMember() {

		MongoClient mongoClient = SKBeanUtils.getLocalSpringBeanManager().getMongoClient();
		MongoDatabase database = mongoClient.getDatabase("imapi");
		MongoCollection<Document> collection = database.getCollection("user");
		if(0==collection.count()) {
			log.info("没有 用户数量 不需要 执行 修改 数据库代码 ====>");
			return;
		}
		MongoDatabase database1 = mongoClient.getDatabase("imRoom");
		MongoCollection<Document> addressbook = database1.getCollection("shiku_room_member");	
		MongoCursor<ObjectId> mongoCursor = addressbook.distinct("roomId", ObjectId.class).iterator();
		Document query=null;
		 MongoCursor<Document> iterator=null;
		 Document result=null;
		 long start=System.currentTimeMillis();
		 long oneCount=0;
		 long allCount=0;
		 MongoCollection<Document> collection2=null;
		while (mongoCursor.hasNext()) {
			ObjectId roomId=mongoCursor.next();
			query=new Document("roomId",roomId);
			 oneCount=addressbook.count(query);
			 if(0==oneCount) {
				 log.info("userId "+roomId+" 没有数据 。。。。");
				 continue;
			 }
			 allCount+=oneCount;
			 log.info("userId "+roomId+" 的手机联系人 列表正在分表分库 =====》 数量  ===> "+addressbook.count(query));
			  collection2 = SKBeanUtils.getRoomManagerImplForIM().getCollection(roomId); 
			if(0< collection2.count(query)) {
				log.info("userId "+roomId+" 分表已存在数据  ====>");
				continue;
			}
			 iterator = addressbook.find(query).iterator();
			 
			 try {
				 while (iterator.hasNext()) {
					 result=iterator.next();
					 if(0<collection2.count(new Document("_id",result.getObjectId("_id")))) {
						 continue;
					 }
					 collection2.insertOne(result);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				iterator.close();
			}
		}
		log.info("分表执行完毕 总数量  ==》 "+allCount+"  总耗时 "+(System.currentTimeMillis()-start)/1000 +" 秒 =====》");
	
	}

	public void updateRoomMemberJid() {

		MongoClient mongoClient = SKBeanUtils.getLocalSpringBeanManager().getMongoClient();
		MongoDatabase database = mongoClient.getDatabase("imapi");
		MongoCollection<Document> collection = database.getCollection("user");
		if(0==collection.count()) {
			log.info("没有 用户数量 不需要 执行 修改 数据库代码 ====>");
			return;
		}
		MongoDatabase database1 = mongoClient.getDatabase("imRoom");
		MongoCollection<Document> addressbook = database1.getCollection("shiku_room_member");	
		MongoCursor<Document> mongoCursor = addressbook.find().iterator();
		Document query=null;
		 MongoCursor<Document> iterator=null;
		 Document result=null;
		 long start=System.currentTimeMillis();
		 long oneCount=0;
		 long allCount=0;
		 MongoCollection<Document> collection2=null;
		while (mongoCursor.hasNext()) {
			Document next = mongoCursor.next();
			Integer userId = next.getInteger("userId");
			query=new Document("userId",userId);
			 oneCount=addressbook.count(query);
			 if(0==oneCount) {
				 log.info("shiku_room_member 没有数据 。。。。");
				 continue;
			 }
			 allCount+=oneCount;
			 log.info("userId "+userId+" 的手机联系人 列表正在分表分库 =====》 数量  ===> "+addressbook.count(query));
			  collection2 = SKBeanUtils.getRoomManagerImplForIM().getCollection(userId); 
			if(0< collection2.count(query)) {
				log.info("userId "+userId+" 分表已存在数据  ====>");
				//continue;
			}
			 iterator = addressbook.find(query).iterator();
			 
			 
			 try {
				 while (iterator.hasNext()) {
					 result=iterator.next();
					 Document document = new Document();
					 String jid = SKBeanUtils.getRoomManagerImplForIM().queryRoomJid(new ObjectId(String.valueOf(result.get("roomId"))));
					 document.append("userId", result.get("userId")).append("jid", jid).append("roomId", result.get("roomId"));
					 
					 if(0<collection2.count(new Document("_id",result.getObjectId("_id")))) {
						 continue;
					 }
					 collection2.insertOne(document);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				iterator.close();
			}
		}
		log.info("分表执行完毕 总数量  ==》 "+allCount+"  总耗时 "+(System.currentTimeMillis()-start)/1000 +" 秒 =====》");
	
	}
	
	public void updateFriends(){

		MongoClient mongoClient = SKBeanUtils.getLocalSpringBeanManager().getMongoClient();
		MongoDatabase database = mongoClient.getDatabase("imapi");
		MongoCollection<Document> collection = database.getCollection("user");
		if(0==collection.count()) {
			log.info("没有 用户数量 不需要 执行 修改 数据库代码 ====>");
			return;
		}
		MongoCollection<Document> addressbook = database.getCollection("u_friends");	
//		Integer userId=10012256;
		//Integer endId=userId+2000;
		MongoCursor<Integer> mongoCursor = addressbook.distinct("userId", Integer.class).iterator();
		Document query=null;
		 MongoCursor<Document> iterator=null;
		 Document result=null;
		 long start=System.currentTimeMillis();
		 long oneCount=0;
		 long allCount=0;
		 MongoCollection<Document> collection2=null;
		 try {
			 while (mongoCursor.hasNext()) {
					Integer userId=mongoCursor.next();
					if(null==userId)
						continue;
					query=new Document("userId",userId);
					 oneCount=addressbook.count(query);
					 if(0==oneCount) {
						 log.info("userId "+userId+" 没有数据 。。。。");
						 continue;
					 }
					 allCount+=oneCount;
					 log.info("userId "+userId+" 的手机联系人 列表正在分表分库 =====》 数量  ===> "+addressbook.count(query));
					  collection2 = SKBeanUtils.getLocalSpringBeanManager().getFriendsManager().getCollection(userId);
					if(0< collection2.count(query)) {
						log.info("userId "+userId+" 分表已存在数据  ====>");
						//continue;
					}
					 iterator = addressbook.find(query).iterator();
					try {
						 while (iterator.hasNext()) {
							 result=iterator.next();
							 if(0<collection2.count(new Document("_id",result.getObjectId("_id")))) {
								 continue;
							 }
							 collection2.insertOne(result);
						}
					} finally {
						if(null!=iterator)
							iterator.close();
					}
				}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			if(null!=mongoCursor)
				mongoCursor.close();
		}
		
		log.info("分表执行完毕 总数量  ==》 "+allCount+"  总耗时 "+(System.currentTimeMillis()-start)/1000 +" 秒 =====》");
		
	}
	

	
}
